package com.zhihao.domain.strategy.service.rule.chain.impl;

import com.zhihao.domain.strategy.repository.IStrategyRepository;
import com.zhihao.domain.strategy.service.armory.IStrategyDispatch;
import com.zhihao.domain.strategy.service.rule.chain.AbstractLogicChain;
import com.zhihao.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import com.zhihao.types.common.Constants;
import com.zhihao.types.enums.ResponseCode;
import com.zhihao.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author Jackson
 * @create 2025/3/12 13:01
 * @description 责任链：权重抽奖策略
 */
@Slf4j
@Component("rule_weight")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class RuleWeightLogicChain extends AbstractLogicChain {

    @Resource
    private IStrategyRepository repository;

    @Resource
    private IStrategyDispatch strategyDispatch;


    /* 策略没配置权重策略的话，RuleWeightLogicChain不会存在于责任链中，所以无需考虑无权重配置的执行了此方法 */
    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        log.info("抽奖责任链-权重开始 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());

        // 1.查询策略的权重配置
        String ruleValue = repository.queryStrategyRuleValue(strategyId, this.ruleModel());
        if (ruleValue == null) {
            throw new AppException(ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getCode(),ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getInfo());
        }

        Map<Long, String> analyticalValueGroup = getAnalyticalValue(ruleValue);
        if (null == analyticalValueGroup || analyticalValueGroup.isEmpty()) {
            log.warn("抽奖责任链-权重告警【策略配置权重，但ruleValue未配置相应值】 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
            return next().logic(userId, strategyId);
        }

        List<Long> analyticalSortedKeys = new ArrayList<>(analyticalValueGroup.keySet());   // .keySet()无序：maybe[6000, 4000, 5000]

        Integer userScore = repository.queryActivityAccountTotalUseCount(userId, strategyId);

        // 找出最小符合的值，也就是【4500 积分，能找到 4000:102,103,104,105】、【5000 积分，能找到 5000:102,103,104,105,106,107】
        Long nextValue = analyticalSortedKeys.stream()
                .sorted(Collections.reverseOrder())
                .filter(key -> userScore >= key)    // 4500 [4000]  5500 [5000,4000]  3000 [](nextValue=null)
                .findFirst()
                .orElse(null);

        // 用户积分大于权重策略最小区间---责任链接管，权重抽奖
        if (null != nextValue) {
            Integer awardId = strategyDispatch.getRandomAwardId(strategyId, analyticalValueGroup.get(nextValue));
            log.info("抽奖责任链-权重接管 userId: {} strategyId: {} ruleModel: {} awardId: {}", userId, strategyId, ruleModel(), awardId);
            return DefaultChainFactory.StrategyAwardVO.builder()
                    .awardId(awardId)
                    .logicModel(ruleModel())
                    .build();
        }

        // 暂不符合权重策略，进行后续责任链过滤
        log.info("抽奖责任链-权重放行 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
        return this.next().logic(userId, strategyId);
    }

    @Override
    protected String ruleModel() {
        return DefaultChainFactory.LogicModel.RULE_WEIGHT.getCode();
    }

    /*
    解析某个rule_weight的rule_value：String 4000:103,104,105... ---> Map<4000,4000:103,104,105   5000,5000:104,...>
 */
    private Map<Long, String> getAnalyticalValue(String ruleValue) {
        String[] ruleValueGroups = ruleValue.split(Constants.SPACE);
        Map<Long, String> ruleValueMap = new HashMap<>();
        for (String ruleValueKey : ruleValueGroups) {
            // 检查输入是否为空
            if (ruleValueKey == null || ruleValueKey.isEmpty()) {
                return ruleValueMap;
            }
            // 分割字符串以获取键和值
            String[] parts = ruleValueKey.split(Constants.COLON);
            if (parts.length != 2) {
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueKey);
            }
            ruleValueMap.put(Long.parseLong(parts[0]), ruleValueKey);
        }
        return ruleValueMap;
    }

}
